package P002;

import org.junit.Test;

/**
 * @Author DJ同学
 * @Date 2021/2/7 13:21
 * @Version 1.0
 * @Name 两数相加
 * @Problem https://leetcode-cn.com/problems/add-two-numbers/submissions/
 */

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode l3 = new ListNode();
        ListNode root = l3;
        int carry = 0;//进位
        while(l1!=null||l2!=null||carry!=0){//注意：当进位不等于0的时候还是需要进入循环
            int num1 = l1!=null?l1.val:0;
            int num2 = l2!=null?l2.val:0;
            int sum = num1+num2+carry;
            ListNode nextNode = new ListNode(sum%10);
            carry = sum/10;
            l3.next = nextNode;
            l3 = nextNode;
            if(l1!=null)    l1 = l1.next;
            if(l2!=null)    l2 = l2.next;
        }
        return root.next;
    }
    @Test
    public void test01(){
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);
        l1.next.next = new ListNode(9,null);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9,null);

        ListNode l3 = addTwoNumbers(l1,l2);
        while(l3!=null){
            System.out.println(l3.val);
            l3 = l3.next;
        }
    }
}



